package com.yx.advice;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.Date;

/**
 * @Classname Myadvice
 * @Date 2021/05/18 17:37
 * @Created by yx
 * @Description TODO:@Component===>组件;@Aspect===>aop增强类(通知)
 */
@Component
@Aspect
public class Myadvice {
    /**
     * @Author:yx
     * @return void
     * @Date 2021/05/18 17:39
     * @param
     * @Description:使用空方法设置切点表达式,后面其它增强也可以使用方法名来找到设置的切点表达式
     **/
    @Pointcut("execution(* com.yx.service..*.*(..))")
    public void pointCut(){}

    /**
     * @Author:yx
     * @return void
     * @Date 2021/05/18 17:47
     * @param joinPoint
     * @Description:前置增强,应用pointCut()方法设置的切点表达式
     **/
    @Before("pointCut()")
    public void before(JoinPoint joinPoint){
        System.out.println("前置通知"+new Date()+":执行了-->"+joinPoint.getSignature().getName()+"方法");
        System.out.println("方法参数列表"+ Arrays.toString(joinPoint.getArgs()));
    }

    /**
     * @Author:yx
     * @return void
     * @Date 2021/05/18 17:51
     * @param joinPoint
     * @param returnObject
     * @Description:后置增强,returning = "returnObject"===>后置增强方法返回值returnObject
     **/
    @AfterReturning(value = "pointCut()",returning = "returnObject")
    public void after(JoinPoint joinPoint,Object returnObject){
        System.out.println("后置通知"+new Date()+":执行了-->"+joinPoint.getSignature().getName()+"方法");
        System.out.println("方法参数列表"+ Arrays.toString(joinPoint.getArgs()));
        System.out.println("返回值"+returnObject);
    }

    /**
     * @Author:yx
     * @return java.lang.Object
     * @Date 2021/05/18 17:56
     * @param proceedingJoinPoint
     * @Description:环绕增强
     **/
    @Around("pointCut()")
    public Object interceptor(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        System.out.println("环绕通知前置"+new Date()+":执行了-->"+proceedingJoinPoint.getSignature().getName()+"方法");
        Object proceed = proceedingJoinPoint.proceed();
        System.out.println("环绕通知后置"+new Date()+":执行了-->"+proceedingJoinPoint.getSignature().getName()+"方法");
        System.out.println("方法参数列表"+ Arrays.toString(proceedingJoinPoint.getArgs()));
        return proceed;
    }

    /**
     * @Author:yx
     * @return void
     * @Date 2021/05/18 19:47
     * @param joinPoint
     * @param e
     * @Description:异常增强    throwing = "e"异常增强方法运行中出现的运行时异常,诺设置全部异常回滚,则检查异常也会捕获
     **/
    @AfterThrowing(value = "pointCut()",throwing = "e")
    public void ThrowExe(JoinPoint joinPoint,Exception e){
        System.out.println("异常增强"+new Date()+"-->方法名:"+joinPoint.getSignature().getName());
        System.out.println("方法参数列表"+ Arrays.toString(joinPoint.getArgs()));
        System.out.println("异常信息:"+e.getMessage());
    }
}
